<?php

namespace Johnm\Probackend\Controllers;

use Input;
use View;
use Lang;
use Cartalyst\Sentry\Sentry as Sentry;
use Illuminate\Support\Facades\Validator;
use Johnm\Probackend\Datatable\Facades\DatatableFacade as Datatable;
use Illuminate\Support\Collection;

class AdministratorUserController extends CoreController {

    private $sentry;

    public function __construct(Sentry $sentry) {
        $this->sentry = $sentry;
    }

    /**
     * Get validation rule for update/storge administrator group
     * 
     * @param integer $id
     * @return array
     */
    private function rules($id = null) {
        if ($id == null) {
            return [
                'email' => "required|email|max:255|unique:users,email",
                'password' => "required|max:255|min:6|confirmed",
                'firstname' => "required|max:255",
                'lastname' => "required|max:255",
                'mobile' => "required|max:20|min:9",
                'address' => "max:255"
            ];
        } else {
            return [
                'email' => "required|email|max:255|unique:users,email,$id",
                'firstname' => "required|max:255",
                'lastname' => "required|max:255",
                'mobile' => "required|max:20",
            ];
        }
    }

    /**
     * Show the api for datatable get data of administrator group
     * 
     * @return json string
     */
    public function datatable() {
        $users = $this->sentry->findAllUsers();
        return Datatable::collection(new Collection($users))
                        ->showColumns('id', 'email', 'first_name', "last_name", "mobile", "address")
                        ->searchColumns('email', 'first_name', "last_name", "mobile", "address")
                        ->orderColumns('id', 'first_name', "last_name", "mobile", "address")
                        ->make();
    }

    /**
     * Display a listing of the administrator group.
     *
     * @return Response
     */
    public function index() {       
        $this->layout->content = View::make('probackend::administrator_user.index');
    }

    /**
     * Show the form for creating a new administrator group.
     *
     * @return Response
     */
    public function create() {
        return View::make('probackend::administrator_user.create', array("groups" => $this->sentry->findAllGroups()));
    }

    /**
     * Store a newly created administrator group in storage.
     *
     * @return Response
     */
    public function store() {
        // get all input data
        $data = Input::all();

        // create validator for validate input data
        $validator = Validator::make($data, $this->rules(), Lang::get("probackend::administrator_user_validator"));

        // validate data
        if ($validator->fails()) {
            // Input data have errors. Response to client
            return json_encode([
                'success' => 0,
                'title' => Lang::get("probackend::administrator_user.message_storge_error_title"),
                'messages' => $validator->messages()->all()
            ]);
        } else {
            // Input data haven't validate error
            $user = $this->sentry->createUser(array(
                'email' => $data['email'],
                'password' => $data['password'],
                'first_name' => $data['firstname'],
                'last_name' => $data['lastname'],
                'mobile' => $data['mobile'],
                'address' => $data['address'],
                'avatar' => $data['avatar'],
                'activated' => true,
                'su' => isset($data['su']) ? 1 : 0,
            ));

            if (isset($data['groups'])) {
                foreach ($data['groups'] as $groupId) {
                    $user->addGroup($this->sentry->findGroupById($groupId));
                }
            }

            return json_encode([
                'success' => 1,
                'title' => Lang::get("probackend::administrator_user.message_storge_success_title"),
                'messages' => [Lang::get("probackend::administrator_user.message_storge_success")]
            ]);
        }
    }

    /**
     * Display the specified administrator group.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) {
        $user = $this->sentry->findUserById($id);
        return View::make("probackend::administrator_user.show", array_merge($user->toArray(), array("groups" => $user->getGroups())));
    }

    /**
     * Show the form for editing the specified administrator group.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id) {
        $user = $this->sentry->findUserById($id);
        return View::make("probackend::administrator_user.edit", array_merge(array('user' => $user), array("c_groups" => $user->getGroups(), "groups" => $this->sentry->findAllGroups())));
    }

    /**
     * Update the specified administrator group in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id) {
        $data = Input::all();
        $validator = Validator::make($data, $this->rules($id), Lang::get("probackend::administrator_user_validator"));
        if ($validator->fails()) {
            return json_encode([
                'success' => 0,
                'title' => Lang::get("probackend::administrator_user.message_update_error_title"),
                'messages' => $validator->messages()->all(),
            ]);
        } else {
            $user = $this->sentry->findUserById($id);
            $user->email = $data['email'];
            $user->first_name = $data['firstname'];
            $user->last_name = $data['lastname'];
            $user->mobile = $data['mobile'];
            $user->address = $data['address'];
            $user->avatar = $data['avatar'];
            $user->su = isset($data['su']) ? 1 : 0;


            // Reset groiup
            foreach ($this->sentry->findAllGroups() as $group) {
                $user->removeGroup($group);
            }

            if (isset($data['groups'])) {
                //update group
                foreach ($data['groups'] as $groupId) {
                    $user->addGroup($this->sentry->findGroupById($groupId));
                }
            }


            if ($user->save()) {
                return json_encode([
                    'success' => 1,
                    'title' => Lang::get("probackend::administrator_user.message_update_success_title"),
                    'messages' => [Lang::get("probackend::administrator_user.message_update_success")]
                ]);
            } else {
                return json_encode([
                    'success' => 0,
                    'title' => Lang::get("probackend::administrator_user.message_update_error_title"),
                    'messages' => [Lang::get("probackend::administrator_user.message_update_error")],
                ]);
            }
        }
    }

    /**
     * Remove the specified administrator group from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id) {
        $user = $this->sentry->findUserById($id);
        if ($user->delete()) {
            return json_encode([
                'success' => 1,
                'title' => Lang::get("probackend::administrator_user.message_delete_success_title"),
                'messages' => [Lang::get("probackend::administrator_user.message_delete_success")]
            ]);
        } else {
            return json_encode([
                'success' => 0,
                'title' => Lang::get("probackend::administrator_user.message_delete_error_title"),
                'messages' => [Lang::get("probackend::administrator_user.message_delete_error")],
            ]);
        }
    }

}
